package com.liwq.base.bolckqueue;

import com.sun.deploy.util.StringUtils;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author : liwq
 * @version : 1.0
 * @date : 2023/2/22
 **/
class MyResource {
    private volatile boolean FLAG = true;
    private AtomicInteger atomicInteger = new AtomicInteger();
    BlockingQueue<String> blockingQueue = null;

    public MyResource(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    public void myProd() throws InterruptedException {
        String data = null;
        boolean retValue;
        //当flag = true 时候，开始生产
        while (FLAG) {
            data = atomicInteger.incrementAndGet()+"";
            retValue = blockingQueue.offer(data,2L, TimeUnit.SECONDS);
            if(retValue){
                System.out.println(Thread.currentThread().getName()+"生成数据成功"+data);
            }else{
                System.out.println(Thread.currentThread().getName()+"生成数据失败"+data);
            }

            TimeUnit.SECONDS.sleep(1);
        }

        //while 外层，代表FLAG为false,停止生产
        System.out.println(Thread.currentThread().getName()+"停止生成数据");
    }

    public void myConsumer() throws InterruptedException {
        String retValue;
        //当flag = true 时候，开始消费
        while (FLAG) {
            retValue = blockingQueue.poll(2L, TimeUnit.SECONDS);
            if(retValue != null && retValue!= ""){
                System.out.println(Thread.currentThread().getName()+"消费数据成功"+retValue);
            }else{
                FLAG = false;
                System.out.println(Thread.currentThread().getName()+"消费数据失败"+retValue);
                return;
            }

        }
    }


}

public class ProdConsumerBlockingQueueDemo {

    public static void main(String[] args) {
        MyResource myResource = new MyResource(new ArrayBlockingQueue<String>(10));

        new Thread(()->{
            try {
                myResource.myProd();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"prod 线程").start();


        new Thread(()->{
            try {
                myResource.myConsumer();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"consumer 线程").start();
    }




}
